package com.xianggu.test;

import com.xianggu.tomcat.SocketProcessor;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

public class SimpleServer implements Runnable {

    private Socket socket;

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8081);

            ExecutorService executorService = new ScheduledThreadPoolExecutor(10);
            System.out.println("服务器已启动，等待请求...");
            while (true) {
                Socket socket = serverSocket.accept();
                executorService.execute(new SimpleServer(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void analyRequest2(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        boolean isHeaderEnd = false;
        while ((line = reader.readLine()) != null && !isHeaderEnd) {
            if (line.isEmpty()) {
                isHeaderEnd = true;
            } else {
                // 可以在这里处理响应头信息，如获取状态码、Content - Length等
            }
        }


        StringBuilder body = new StringBuilder();
        int i = 0;
        while ((line = reader.readLine()) != null) {
            body.append(line).append("\r\n");
            System.out.println("读取到" + ++i + "行：" + line);
        }
        System.out.println("请求体内容: " + body.toString());
        reader.close();
    }
    private static void analyRequest(InputStream inputStream) throws IOException {
        // 使用 BufferedInputStream 包装，支持 mark/reset 复用流
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        bis.mark(Integer.MAX_VALUE);

        // 解析请求头
        Map<String, String> headers = new HashMap<>();
        StringBuilder headerBuilder = new StringBuilder();
        int b;
        while ((b = bis.read()) != -1) {
            headerBuilder.append((char) b);
            // 检查是否到达请求头结束标记 "\r\n\r\n"
            if (headerBuilder.length() >=4 &&
                    headerBuilder.substring(headerBuilder.length()-4).equals("\r\n\r\n")) {
                break;
            }
        }
        String[] headerLines = headerBuilder.toString().split("\r\n");
        for (String line : headerLines) {
            if (line.contains(":")) {
                String[] parts = line.split(":", 2);
                headers.put(parts[0].trim().toLowerCase(), parts[1].trim());
            }
        }

        // 根据 Content-Length 或 Transfer-Encoding 解析请求体
        byte[] bodyBytes;
        if (headers.containsKey("content-length")) {
            int contentLength = Integer.parseInt(headers.get("content-length"));
            bodyBytes = new byte[contentLength];
            bis.read(bodyBytes);
        } else if (headers.containsKey("transfer-encoding") &&
                headers.get("transfer-encoding").equalsIgnoreCase("chunked")) {
            // 解析分块传输编码
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            while (true) {
                String chunkSizeLine = readChunkSizeLine(bis);
                int chunkSize = Integer.parseInt(chunkSizeLine.trim(), 16);
                if (chunkSize == 0) {
                    break;
                }
                byte[] chunk = new byte[chunkSize];
                bis.read(chunk);
                buffer.write(chunk);
                bis.skip(2); // 跳过 "\r\n"
            }
            bodyBytes = buffer.toByteArray();
        } else {
            // 无 Content-Length 且非分块传输，视为无请求体
            bodyBytes = new byte[0];
        }

        // 根据 Content-Type 的 charset 解码（示例用 UTF-8）
        String charset = "UTF-8";
        if (headers.containsKey("content-type")) {
            String[] parts = headers.get("content-type").split(";");
            for (String part : parts) {
                if (part.trim().startsWith("charset=")) {
                    charset = part.split("=", 2)[1].trim();
                }
            }
        }
        String requestBody = new String(bodyBytes, charset);
        System.out.println("请求体内容: " + requestBody);

        // 重置流以便后续处理
        bis.reset();
    }

    // 读取分块大小行
    private static String readChunkSizeLine(InputStream bis) throws IOException {
        StringBuilder sb = new StringBuilder();
        int b;
        while ((b = bis.read()) != -1) {
            if (b == '\r') {
                bis.read(); // 跳过 '\n'
                break;
            }
            sb.append((char) b);
        }
        return sb.toString();
    }
    @Override
    public void run() {

        try {
            InputStream inputStream = socket.getInputStream();
            analyRequest(inputStream);

            OutputStream outputStream = socket.getOutputStream();
            // 读取请求内容（这里简单处理，不做完整解析）
            byte[] buffer = new byte[1024];
            int length = inputStream.read(buffer);
            String request = new String(buffer, 0, length);
            // 判断请求路径是否为 /666/user
            if (request.contains("GET /666/user")) {
                String response = "这是测试内容2";
                outputStream.write(("HTTP/1.1 200 OK\r\n" +
                        "Content - Length: " + response.length() + "\r\n" +
                        "Content - Type: text/plain\r\n" +
                        "\r\n" + response).getBytes());
            } else {
                // 如果不是目标请求，返回404
                String notFound = "404 Not Found";
                outputStream.write(("HTTP/1.1 404 Not Found\r\n" +
                        "Content - Length: " + notFound.length() + "\r\n" +
                        "Content - Type: text/plain\r\n" +
                        "\r\n" + notFound).getBytes());
            }
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public SimpleServer(Socket socket) {
        this.socket = socket;
    }
}